package cn.buk.qms.web;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

import cn.buk.common.JsonResult;
import cn.buk.common.dto.CommonDto;
import cn.buk.tms.dto.TrainOrderDto;
import cn.buk.tms.dto.TrainOrderPassengerDto;
import cn.buk.tms.entity.misc.OperationLog;
import cn.buk.tms.train.sc.TrainOrderSearchCriteria;
import cn.buk.tms.train.service.TrainOrderService;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author yfdai
 */
@RestController
@RequestMapping("/train")
public class TrainOrderController extends BaseController {

    private static final Logger logger = LogManager.getLogger(TrainOrderController.class);

    @Autowired
    private TrainOrderService trainOrderService;

    /**
     * 搜索火车票订单
     * @param request
     * @param sc
     * @return
     */
    @RequestMapping("/orders")
    public CommonDto<TrainOrderDto> searchTrainOrders(HttpServletRequest request,
                                                    @ModelAttribute("sc") TrainOrderSearchCriteria sc) {
        final int enterpriseId = getEnterpriseId(request);
        final int userId = getUserId(request);

        List<TrainOrderDto> datas = trainOrderService.searchTrainOrders(enterpriseId, userId, sc);

        CommonDto<TrainOrderDto> commonDto = new CommonDto<>();
        commonDto.setDataList(datas);
        commonDto.setPage(sc.getPage());

        return commonDto;
    }

    /**
     * 获取火车票订单详情
     * @param request
     * @return
     */
    @RequestMapping("/order/{orderId}")
    public TrainOrderDto searchTrainOrders(HttpServletRequest request,
                                        @PathVariable("orderId") final int orderId) {
        final int enterpriseId = getEnterpriseId(request);

        return trainOrderService.getTrainOrderById(enterpriseId, getUserId(request), orderId);
    }

    /**
     * 创建火车票订单
     * @param request
     * @param dto
     * @return
     */
    @RequestMapping(value = "/order", consumes = "application/json", method = RequestMethod.POST)
    public JsonResult createTrainOrder(HttpServletRequest request,
                                       @RequestBody TrainOrderDto dto) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return trainOrderService.createTrainOrder(enterpriseId, username, dto);
    }

    /**
     * 通过上传excel文件，生成火车票订单
     * @param request
     * @param upfile
     * @return
     */
    @RequestMapping(value = "/orders/upload", method = POST)
    public JsonResult uploadTrainOrders(HttpServletRequest request,
        MultipartFile upfile,
        @RequestParam(value = "supplierId", defaultValue = "0") int supplierId,
        @RequestParam(value = "paymentMethodId", defaultValue = "0") int paymentMethodId
    ) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        if (supplierId < 1) {
            return JsonResult.createJsonResult(-2, "请选择供应商");
        }

        if (paymentMethodId < 1) {
            return JsonResult.createJsonResult(-3, "请选择支出方式");
        }

        //Now do something with file...
        String fileName = new String(upfile.getOriginalFilename().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

        String filePath = System.getProperty("java.io.tmpdir") +  File.separator + fileName;
        logger.info(filePath);
        File outputFile = new File(filePath);
        try {
            FileCopyUtils.copy(upfile.getBytes(), outputFile);
        } catch (IOException e) {
            e.printStackTrace();
            return JsonResult.createJsonResult(-1, "文件处理失败");
        }

        return trainOrderService.createTrainOrderByExcel(enterpriseId, username, filePath, supplierId, paymentMethodId);
    }

    /**
     * 修改订单的备注
     * @param request
     * @param orderId
     * @param remark
     * @return
     */
    @RequestMapping(value = "/order/{orderId}/remark", method = RequestMethod.POST)
    public JsonResult updateTrainOrderRemark(HttpServletRequest request,
                                             @PathVariable("orderId") final int orderId,
                                             @RequestParam("remark") String remark) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return trainOrderService.updateTrainOrderRemark(enterpriseId, username, orderId, remark);
    }

    /**
     * 修改外部订单号
     * @param request
     * @param orderId
     * @param externalOrderNo
     * @return
     */
    @RequestMapping(value = "/order/{orderId}/externalOrderNo", method = RequestMethod.POST)
    public JsonResult updateTrainOrderExternalOrderNo(HttpServletRequest request,
                                             @PathVariable("orderId") final int orderId,
                                             @RequestParam("externalOrderNo") String externalOrderNo) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return trainOrderService.updateTrainOrderExternalOrderNo(enterpriseId, username, orderId, externalOrderNo);
    }

    /**
     * 修改订单的供应商
     * @param request
     * @param orderId
     * @param supplierId
     * @return
     */
    @RequestMapping(value = "/order/{orderId}/supplier", method = RequestMethod.POST)
    public JsonResult updateTrainOrderSupplier(HttpServletRequest request,
                                             @PathVariable("orderId") final int orderId,
                                             @RequestParam("supplierId") int supplierId) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return trainOrderService.updateTrainOrderSupplier(enterpriseId, username, orderId, supplierId);
    }

    /**
     * 修改订单的对外支付方式
     * @param request
     * @param orderId
     * @param paymentMethodId
     * @return
     */
    @RequestMapping(value = "/order/{orderId}/paymentMethod", method = RequestMethod.POST)
    public JsonResult updateTrainOrderPaymentMethod(HttpServletRequest request,
                                               @PathVariable("orderId") final int orderId,
                                               @RequestParam("paymentMethodId") int paymentMethodId) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return trainOrderService.updateTrainOrderPaymentMethod(enterpriseId, username, orderId, paymentMethodId);
    }

    /**
     * 修改订单的价格
     */
    @RequestMapping(value = "/order/{orderId}/price", method = RequestMethod.POST)
    public JsonResult updateTrainOrderPrice(HttpServletRequest request,
                                          @PathVariable("orderId") int orderId,
                                          @RequestParam("price") double price,
                                          @RequestParam("serviceCharge") double serviceCharge,
                                          @RequestParam("cost") double cost
    ) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return trainOrderService.updateTrainOrderPrice(enterpriseId, username, orderId, price, cost, serviceCharge);
    }

    /**
     * 修改订单的乘车人信息
     */
    @RequestMapping(value = "/order/{orderId}/passenger", method = RequestMethod.POST)
    public JsonResult updateTrainOrderPassenger(HttpServletRequest request,
                                            @PathVariable("orderId") int orderId,
                                            @RequestParam("psgId") int psgId,
                                            @RequestParam("name") String name,
                                            @RequestParam("mobile") String mobile,
                                            @RequestParam("coachNo") String coachNo,
                                            @RequestParam("seatNo") String seatNo) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        TrainOrderPassengerDto psgDto = new TrainOrderPassengerDto();
        psgDto.setId(psgId);
        psgDto.setName(name);
        psgDto.setMobile(mobile);
        psgDto.setCoachNo(coachNo);
        psgDto.setSeatNo(seatNo);

        return trainOrderService.updateTrainOrderPassenger(enterpriseId, username, orderId, psgDto);
    }

    /**
     * 开始处理火车票订单
     * @param request
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/order/{orderId}/status/processing", method = RequestMethod.POST)
    public JsonResult processTrainOrder(HttpServletRequest request,
                                                     @PathVariable("orderId") final int orderId) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return trainOrderService.processTrainOrder(enterpriseId, username, orderId);
    }

    /**
     * 火车票订单处理完毕
     * @param request
     * @param orderId
     * @param remark
     * @return
     */
    @RequestMapping(value = "/order/{orderId}/status/finished", method = RequestMethod.POST)
    public JsonResult finishTrainOrder(HttpServletRequest request,
                                        @PathVariable("orderId") final int orderId,
                                       @RequestParam("remark") String remark) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return trainOrderService.finishTrainOrder(enterpriseId, username, orderId, remark);
    }

    @RequestMapping(value = "/order/{orderId}/status/canceled", method = RequestMethod.POST)
    public JsonResult cancelTrainOrder(HttpServletRequest request,
                                       @PathVariable("orderId") final int orderId,
                                       @RequestParam("remark") String remark) {
        final int enterpriseId = getEnterpriseId(request);
        final String username = getUsername(request);

        return trainOrderService.cancelTrainOrder(enterpriseId, username, orderId, remark);
    }

    @RequestMapping(value = "/order/{orderId}/history")
    public List<OperationLog> searchTrainOrderHistory(HttpServletRequest request,
                                                      @PathVariable("orderId") final int orderId) {
        final int enterpriseId = getEnterpriseId(request);

        return trainOrderService.searchTrainOrderHistory(enterpriseId, orderId);
    }
}
